import { defineStore } from 'pinia'
import * as qs from 'query-string'
import useHttp from '@renderer/utils/http'
import { store } from '..'
import { useLocalStorage } from '@vueuse/core'
import dayjs from 'dayjs'
interface DefaultSpu {
  brand?: string
  name: string
  category_id: string
  code: string
  default_sku: any | null
  description?: string
  dynamicCategory?: string
  exchange_fee: number
  id: number
  imgs: any
  integral: number
  is_exchange_fee: boolean
  is_integral: number
  is_recommend: number
  sales: number
  score: number
  sell_point: any
  sort: number
  unit: string
  video?: string
  price: number
  sale_type?: string[]
  discountPrice?: number
}
const MALL_TYPE = 'mall_type'
const storage = useLocalStorage(MALL_TYPE, null)
export const useListStore = defineStore({
  id: 'list',
  state: () => ({
    list: [] as DefaultSpu[],
    activeCategoryId: null,
    specs: [] as any,
    isRecommend: 0,
    isCombo: 0,
    comboList: [],
    page: storage.value,
    daily: {} as any,
    highest: [] as any,
    dailySpus: [] as any,
    socket: null,
    dailyCombos: [] as any,
    topCategory: 0
  }),
  getters: {
    data(state) {
      return state.isCombo === 1 ? state.comboList : state.list
      // : state.isRecommend
      // ? state.list.filter((l) => state.highest.findIndex((h) => h.id === l.id) === -1)
      // : state.list
    },
    getPage(state) {
      return state.page
    }
  },
  actions: {
    async updateList(name?: string) {
      const { data: res } = await useHttp(
        `/product/c/list?${qs.stringify({
          categoryId: this.activeCategoryId,
          name,
          isRecommend: this.isRecommend
        })}`
      )
        .get()
        .json()
      if (res.value?.code === 200) {
        this.list = res.value.data.map((spu: DefaultSpu) => {
          if (spu.imgs) {
            spu.imgs = JSON.parse(spu.imgs)
          }
          if (spu.default_sku) {
            spu.default_sku = JSON.parse(spu.default_sku)
            spu.price = spu.default_sku?.price
          }
          if (spu.sell_point) {
            spu.sell_point = spu.sell_point.split('\n')
          }
          return spu
        })
      }
    },
    async getSpec(categoryId: number) {
      const { data: res } = await useHttp(`/category/c/list?categoryId=${categoryId}`).get().json()
      if (res.value.code === 200) {
        this.setActiveCategoryId(categoryId)
        this.setSpec([
          {
            name: '全部',
            id: categoryId
          },
          ...res.value.data
        ])
        await this.updateList()
      }
    },
    async updateComboList() {
      const { data: res } = await useHttp('/combo/c/list').get().json()
      if (res.value.code === 200) {
        res.value.data.forEach((data) => {
          if (data.imgs) {
            data.imgs = JSON.parse(data.imgs)
          } else {
            data.imgs = []
          }
          if (data.video) {
            data.video = [data.video]
          } else {
            data.video = []
          }
          if (data.sell_point) {
            data.sell_point = data.sell_point.split('\n')
          } else {
            data.sell_point = []
          }
          data.default_sku = []
          const spus = JSON.parse(data.spus || '[]')
          data.price = 0
          data.discountPrice = 0
          spus.forEach((spu) => {
            const { imgs, video, sell_point, default_sku } = spu
            if (imgs) {
              data.imgs = data.imgs.concat(JSON.parse(imgs))
            }
            if (video) {
              data.video.push(video)
            }
            if (default_sku) {
              const defaultSku = JSON.parse(default_sku)
              defaultSku.discount = spu.discount
              data.default_sku.push(defaultSku)
              data.price =
                data.price + Math.ceil((Number(defaultSku.price) * Number(spu.discount)) / 10)
              data.discountPrice = data.discountPrice + Number(defaultSku.price)
            } else {
              data.price = data.price + Math.ceil((Number(spu.price) * Number(spu.discount)) / 10)
              data.discountPrice = data.discountPrice + Number(spu.price)
            }
            if (sell_point) {
              data.sell_point.push(...sell_point.split('\n'))
            }
          })
        })
        this.comboList = res.value.data
      }
    },
    setActiveCategoryId(id) {
      this.activeCategoryId = id
    },
    setSpec(specs) {
      this.specs = specs
    },
    setIsRecommend(recommend) {
      this.isRecommend = recommend
    },
    setIsCombo(combo) {
      console.log(combo)
      this.isCombo = combo
    },
    setPage(content) {
      storage.value = content
      this.page = content
    },
    setDaily(dailys) {
      const daily = dailys?.[0]
      this.daily = daily
      this.setSpus()
    },
    async setSpus() {
      if (this.daily && this.daily.id) {
        const { data: res } = await useHttp(`/daily/spus?id=${this.daily.id}`).get().json()
        if (res.value.code === 200) {
          this.dailySpus = res.value.data
            .filter((dailySpu) => dailySpu.spu_id)
            .map((dailySpu) => {
              const spu = dailySpu.spu
              if (spu.imgs) {
                spu.imgs = JSON.parse(spu.imgs)
              }
              if (spu.default_sku) {
                spu.default_sku = JSON.parse(spu.default_sku)
                spu.price = spu.default_sku?.price
              }
              if (spu.sell_point) {
                spu.sell_point = spu.sell_point.split('\n')
              }
              return dailySpu
            })
          const dailyCombos = res.value.data.filter((dailyCombo) => dailyCombo.combo_id)
          dailyCombos.forEach((dailyCombo) => {
            const data = dailyCombo.spu?.[0]
            if (data.imgs) {
              data.imgs = JSON.parse(data.imgs)
            } else {
              data.imgs = []
            }
            if (data.video) {
              data.video = [data.video]
            } else {
              data.video = []
            }
            if (data.sell_point) {
              data.sell_point = data.sell_point.split('\n')
            } else {
              data.sell_point = []
            }
            data.default_sku = []
            const spus = JSON.parse(data.spus || '[]')
            data.price = 0
            data.discountPrice = 0
            spus.forEach((spu) => {
              const { imgs, video, sell_point, default_sku } = spu
              if (imgs) {
                data.imgs = data.imgs.concat(JSON.parse(imgs))
              }
              if (video) {
                data.video.push(video)
              }
              if (default_sku) {
                const defaultSku = JSON.parse(default_sku)
                defaultSku.discount = spu.discount
                data.default_sku.push(defaultSku)
                data.price =
                  data.price + Math.ceil((Number(defaultSku.price) * Number(spu.discount)) / 10)
                data.discountPrice = data.discountPrice + Number(defaultSku.price)
              } else {
                data.price = data.price + Math.ceil((Number(spu.price) * Number(spu.discount)) / 10)
                data.discountPrice = data.discountPrice + Number(spu.price)
              }
              if (sell_point) {
                data.sell_point.push(...sell_point.split('\n'))
              }
            })
          })
          this.dailyCombos = dailyCombos.map((dailyCombo) => dailyCombo.spu?.[0])
        }
      }
    },
    async setHighest() {
      const { data: res } = await useHttp('/product/highest').get().json()
      if (res?.value?.code === 200) {
        this.highest = res.value.data.map((spu: DefaultSpu) => {
          if (spu.imgs) {
            spu.imgs = JSON.parse(spu.imgs)
          }
          if (spu.default_sku) {
            spu.default_sku = JSON.parse(spu.default_sku)
            spu.price = spu.default_sku?.price
          }
          if (spu.sell_point) {
            spu.sell_point = spu.sell_point.split('\n')
          }
          return spu
        })
        console.log(this.highest)
      }
    },
    async setSocket(socket) {
      this.socket = socket
    },
    async setList(list) {
      this.list = list
    },
    setTopCategory(category?: number) {
      this.topCategory = category
    },
    order(type, sort) {
      if (type === 'time') {
        this.list = this.list.sort((x, y) => {
          return sort === 'desc'
            ? dayjs(x.update_at).unix() - dayjs(y.update_at).unix()
            : dayjs(y.update_at).unix() - dayjs(x.update_at).unix()
        })
      } else if (type === 'sale') {
        this.list = this.list.sort((x, y) => {
          return sort === 'desc' ? x.sales - y.sales : y.sales - x.sales
        })
      }
    }
  }
})

export const useListStoreWithout = () => useListStore(store)
